package com.telit.firecommand.controller;

import com.telit.common.annotation.Log;
import com.telit.common.constant.Constant;
import com.telit.common.entity.DataReturn;
import com.telit.common.enums.*;
import com.telit.common.util.JwtTokenUtils;
import com.telit.firecommand.dto.NoticePushDTO;
import com.telit.firecommand.dto.PushFireMsg;
import com.telit.firecommand.dto.PushSocketDTO;
import com.telit.firecommand.facade.SmsPushUriPubFacadeService;
import com.telit.firecommand.service.SmsService;
import com.telit.firecommand.service.UserInfoService;
import com.telit.firecommand.service.impl.FireDisposeServiceImpl;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import com.telit.upms.vo.UserListByPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 推送消息API
 * Create by Chencf 2023/01/05
 */
@Slf4j
@RestController
@RequestMapping(value = "/msg", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "推送消息API", value = "推送消息API", produces = MediaType.APPLICATION_JSON_VALUE)
public class MsgController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private FireDisposeServiceImpl fireDisposeService;

    @Autowired
    private SmsPushUriPubFacadeService smsPushUriPubFacadeService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 发送火警信息短信
     *
     * @param noticePushDTO 火警信息
     *
     * @return DataReturn
     */
    @Log(service = ServiceName.FIRE_ALARMS, businessType = BusinessType.BUSINESS_LOG, operatorType = OperatorType.WEB, businessOperatorType = BusinessOperatorType.GJXF)
    @PostMapping(value = "/push-notice")
    @ApiOperation(value = "火情流程处置中-->给用户发送消息", httpMethod = Constant.REQUEST_METHOD_POST)
    public DataReturn pushMsg(@Validated @RequestBody NoticePushDTO noticePushDTO) throws Exception {
        noticePushDTO.setStatus(1);
        //isOpen=1说明需要值守过滤
        noticePushDTO.setIsOpen("1");
        smsService.sendSms(noticePushDTO);
        return DataReturn.ok();
    }

    //webscoker推送消息
    @GetMapping(value = "/pushSocket")
    @ApiOperation(value = "webscoker推送火情信息到web端", httpMethod = Constant.REQUEST_METHOD_GET)
    public DataReturn pushSocket(PushSocketDTO pushSocketDTO) {
        smsService.pushSocket(pushSocketDTO);
        return DataReturn.ok();
    }

    @PostMapping(value = "/pushNotice", produces = "application/json;charset=UTF-8")
    @ApiOperation("行政区划-给用户发送消息")
    public DataReturn pushMsg2(@Validated @RequestBody NoticePushDTO noticePushDTO) {

        /*String realname = JwtTokenUtils.getName();
        List<ForesterDTO> paramForesterDTOList = noticePushDTO.getForesterDTOList();
        List<String> foresterIdList=null;
        if(!CollectionUtils.isEmpty(paramForesterDTOList)){
            foresterIdList=new ArrayList<>();
            for (ForesterDTO foresterDTO:paramForesterDTOList){
                String foresterId = String.valueOf(foresterDTO.getId());
                foresterIdList.add(foresterId);
            }
        }
        if(!CollectionUtils.isEmpty(foresterIdList)){
            // 发送通知
            msgService.pushNotice(foresterIdList);
            foresterIdList.forEach(userId->{
                // 记录发送的信息
                SysUserDetailVo sysUserVo = userInfoService.getUserInfo(Long.valueOf(userId));
                if(sysUserVo != null){
                    msgService.addFireSmsLog(noticePushDTO.getFireId(),sysUserVo.getRealName(),Long.valueOf(userId),sysUserVo.getDeptName(),realname);
                }
            });
        }*/
        try {
            // todo 真实火情短信模版
//            msgService.pushSms(noticePushDTO.getMobileList(),noticePushDTO.getAddress());
            smsPushUriPubFacadeService.sendSms(Long.parseLong(noticePushDTO.getFireId()), noticePushDTO.getMobileList(),
                    1);

           /* //推送人员的用户ID
            List<ForesterDTO> paramForesterDTOList = noticePushDTO.getForesterDTOList();
            List<String> foresterIdList=null;
            if(!CollectionUtils.isEmpty(paramForesterDTOList)){
                foresterIdList=new ArrayList<>();
                for (ForesterDTO foresterDTO:paramForesterDTOList){
                    String foresterId = String.valueOf(foresterDTO.getId());
                    foresterIdList.add(foresterId);
                }
            }

            if(!CollectionUtils.isEmpty(foresterIdList)) {
                //发送WEB通知
                String [] forestIdArray=new String[foresterIdList.size()];
                communicateFeignClient.sendMsg(new SendMessageDTO("special",foresterIdList.toArray(forestIdArray), JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.FIRE_ALARM, null))));
                //推送APP通知
                String content = noticePushDTO.getAddress() + "发现了真实火情,请及时组织扑火工作";
                String title = "发现真实火情";
                AliyunPushMessageUtils.customizeAdvancedPush(new AliPushMessagePojo(MsgConstants.TARGET_ACCOUNT, MsgConstants.PUSH_TYPE_MESSAGE, MsgConstants.DEVICE_TYPE_ANDROID, title, foresterIdList,
                        new AliPushContentPojo(NoticeTypeConstants.NOTICE_TYPE_NORMAL, JSON.toJSONString(content))));

                //查询火情详细信息
                CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(noticePushDTO.getFireId());
                //记录推送记录
                foresterIdList.forEach(e -> {
                    CommMsgCenterLog log = new CommMsgCenterLog(content, "4", new Date(), "1", null==commFireAlarm.getFinderName()?null:commFireAlarm.getFinderName(), title, Long.parseLong(e));
                    commMsgCenterLogDao.insert(log);
                });
            }*/

            //记录火情处置信息
            List<UserListByPageVo> foresterDTOList = noticePushDTO.getForesterDTOList();
            PushFireMsg pushFireMsg = new PushFireMsg();
            pushFireMsg.setFireId(Long.valueOf(noticePushDTO.getFireId()));
            pushFireMsg.setForesterDTOList(foresterDTOList);
            Long id = JwtTokenUtils.getId();
            MicroSysUserAllInfoVo userInfo = userInfoService.getUserInfo(id);
            fireDisposeService.processDisposeInfo(pushFireMsg, userInfo);
            return DataReturn.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return DataReturn.failure(ResultCode.SERVER_ERROR, e.getMessage());
        }
    }

}
